﻿using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Reflection;
using Volo.Abp.Auditing;
using Volo.Abp.Clients;
using Volo.Abp.DependencyInjection;
using Volo.Abp.MultiTenancy;
using Volo.Abp.Timing;
using Volo.Abp.Tracing;
using Volo.Abp.Users;

namespace Jy.Abp.Auditing;

[Dependency(ReplaceServices = true)]
public class JyAbpAuditingHelper : AuditingHelper
{
    public JyAbpAuditingHelper(IAuditSerializer auditSerializer,
                               IOptions<AbpAuditingOptions> options,
                               ICurrentUser currentUser,
                               ICurrentTenant currentTenant,
                               ICurrentClient currentClient,
                               IClock clock,
                               IAuditingStore auditingStore,
                               ILogger<AuditingHelper> logger,
                               IServiceProvider serviceProvider,
                               ICorrelationIdProvider correlationIdProvider) 
        : base(auditSerializer, options, currentUser, currentTenant, currentClient, clock, auditingStore, logger, serviceProvider, correlationIdProvider)
    {
    }

    public override AuditLogActionInfo CreateAuditLogAction(AuditLogInfo auditLog, Type type, MethodInfo method, IDictionary<string, object> arguments)
    {
        //如果是第一个方法，认为是入口 ，写入操作名称
        if (auditLog.Actions.IsNullOrEmpty())
        {
            var typeTagAttribute = type.GetCustomAttribute<AuditTagAttribute>();
            var methodAttribute = method.GetCustomAttribute<AuditTagAttribute>();
            var typeTag = typeTagAttribute?.Tag ?? type.Name;
            var methodTag = methodAttribute?.Tag ?? method.Name;
            auditLog.ExtraProperties["Tag"] = $"{typeTag}-{methodTag}";
        }
        return base.CreateAuditLogAction(auditLog, type, method, arguments);
    }
}
